import { SignJWT, jwtVerify } from 'jose';
import { headers } from 'next/headers'
import httpCode from "@/utils/httpCode.mjs";
export const secret = new TextEncoder().encode(
    'cc7e0d44fd473002f1c42167459001140ec6389b7353f8088f4d9a95f2f596f2',
)

const alg = 'HS256'



export class AuthError extends Error {}
export async function generateToken(playload = {}) {
    const jwt = await new SignJWT({ 'urn:example:claim': true, ...playload })
        .setProtectedHeader({ alg })
        .setIssuedAt()
        .setIssuer('urn:example:issuer')
        .setAudience('urn:example:audience')
        .setExpirationTime('2h')
        .sign(secret)
    return jwt
}
/**
 * Verifies the user's JWT token and returns its payload if it's valid.
 */
export async function verifyAuth(req) {
    // 获取请求头
    const headersList = headers()
    const token = headersList.get('authorization')
    if (!token) throw new AuthError('Your token is missing.')
    try {
        const verified = await jwtVerify(
            token,
            secret
        )
        return verified.payload
    } catch (err) {
        throw new AuthError('Your token has expired.')
    }
}

// console.log(jwt)
// setTimeout(async () => {
//     try {
//         const { payload } = await jwtVerify(jwt, secret);
//         console.log('Decoded Payload:', payload);
//
//         // 获取user_id
//         const userId = payload.user_id;
//         console.log('User ID:', userId);
//     } catch (error) {
//         console.error('Error verifying JWT:', error);
//         if (error.code === 'ERR_JWT_EXPIRED') {
//             console.log('JWT has expired.');
//         }
//     }
// }, 2000)

